package com.wanlian.netty.File.msg;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

import java.nio.charset.Charset;

/**
 * 编码器
 *
 * @author ailianlu2
 */
public class FilePeerMsgEncoder extends MessageToByteEncoder<FilePeerMsg> {
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, FilePeerMsg filePeerMsg, ByteBuf byteBuf) throws Exception {
        FilePeerMsgHead head = filePeerMsg.getHead();
        byteBuf.writeInt(head.getHead_data());
        byteBuf.writeInt(head.getVersion());
        byteBuf.writeInt(head.getMsgType());
        byteBuf.writeInt(head.getMsgLength() + head.getDataLength());
        byteBuf.writeInt(head.getMsgLength());
        byteBuf.writeInt(head.getDataLength());
        FileBaseMsg fileBaseMsg = filePeerMsg.getFileBaseMsg();
        String content = fileBaseMsg.getContent();
        //加入content
        byte[] data = content.getBytes(Charset.forName("UTF-8"));
        if (data != null && data.length > 0) {
            byteBuf.writeBytes(data);
        }
        //加入bytes
        byte[] fileData = fileBaseMsg.getData();
        if (fileData != null && fileData.length > 0) {
            byteBuf.writeBytes(fileData);
        }
    }
}
